package com.vere.rpc.proxy;//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//




import com.vere.rpc.clinet.RemoteClient;
import com.vere.rpc.msg.CallMessage;
import com.vere.rpc.util.ObjectUtil;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class RPCHandler implements InvocationHandler {
    private RemoteClient remoteClient;

    public RPCHandler(RemoteClient remoteClient) {
        this.remoteClient = remoteClient;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        CallMessage callMessage = new CallMessage();
        callMessage.setServiceInterface(method.getDeclaringClass().getName());
        callMessage.setMethodName(method.getName());
        callMessage.setObjects(args);
        callMessage.setTypes(method.getParameterTypes());
        callMessage.setAction(CallMessage.INVOKE);
        SocketChannel socketChannel = this.remoteClient.getSocketChannel();
        Selector selector = this.remoteClient.getSelector();
        ObjectUtil.sendObject(socketChannel, callMessage);
        return this.getRemoteOject(socketChannel, selector);
    }

    private Object getRemoteOject(SocketChannel socketChannel, Selector selector) {
        Iterator iterator = null;

        try {
            selector.select();
            iterator = selector.selectedKeys().iterator();

            while(iterator.hasNext()) {
                SelectionKey selectionKey = (SelectionKey)iterator.next();
                if (selectionKey.isValid() && selectionKey.isReadable()) {
                    Object returnObj = ObjectUtil.receiveObject(socketChannel);
                    return returnObj;
                }
            }
        } catch (Exception var6) {
        }

        return null;
    }
}
